/**
 * 讯飞 Spark Lite 模型 API 服务
 */

interface XunfeiConfig {
  apiKey: string;
  apiSecret: string;
  appId: string;
  apiUrl: string;
}

interface Message {
  role: 'user' | 'assistant' | 'system';
  content: string;
}

interface ChatRequest {
  model: string;
  messages: Message[];
  stream?: boolean;
  temperature?: number;
  max_tokens?: number;
}

interface ChatResponse {
  choices: {
    message: {
      content: string;
      role: string;
    };
    index: number;
    finish_reason: string;
    delta?: {
      content?: string;
      role?: string;
    };
  }[];
  created: number;
  id: string;
  model: string;
  object: string;
  usage?: {
    prompt_tokens: number;
    completion_tokens: number;
    total_tokens: number;
  };
}

// 讯飞 API 配置 - 通过本地代理服务器
const xunfeiConfig: XunfeiConfig = {
  apiKey: '9bf315f669cd77f7cc91a023c0a36f8b',
  apiSecret: 'M2FlNmIzMmRmYzdmYjFjOTU3YzQ4ZjA4',
  appId: '290f4fa9',
  apiUrl: 'http://localhost:3003/api/xunfei/chat' // 使用本地代理
};

/**
 * 调用讯飞 Spark Lite 模型
 * @param messages 对话消息列表
 * @param stream 是否使用流式返回
 * @param onMessage 流式消息回调
 */
export const callXunfeiAPI = async (
  messages: Message[],
  stream: boolean = true,
  onMessage?: (content: string, isComplete?: boolean) => void,
  signal?: AbortSignal // 1. 添加 AbortSignal 参数
): Promise<string | void> => { // 1. 修正返回类型，因为流式调用不返回值
  const requestBody: ChatRequest = {
    model: '4.0Ultra',
    messages: messages,
    stream: stream,
    temperature: 0.7,
    max_tokens: 2048
  };
  if (!stream) {
    // 非流式调用
    const response = await fetch(xunfeiConfig.apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestBody),
      signal, // 2. 将 signal 传递给 fetch
    });

    if (!response.ok) {
      throw new Error(`API request failed: ${response.status}`);
    }

    const data: ChatResponse = await response.json();
    return data.choices[0].message.content;
  } else {
    // 流式调用
    const response = await fetch(xunfeiConfig.apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'text/event-stream'
      },
      body: JSON.stringify(requestBody),
      signal, // 2. 将 signal 传递给 fetch
    });

    if (!response.ok) {
      throw new Error(`API request failed: ${response.status}`);
    }

    const reader = response.body?.getReader();
    const decoder = new TextDecoder();
    if (!reader) {
      throw new Error('Response body is not readable');
    }

    try { // 3. 包裹循环以捕获中止错误
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value, { stream: true });
        const lines = chunk.split('\n');

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const data = line.substring(6);
            
            if (data === '[DONE]') {
              onMessage?.('', true);
              break;
            }

            try {
              const json: ChatResponse = JSON.parse(data);
              const content = json.choices[0]?.delta?.content || '';
              if (content) {
                onMessage?.(content, false);
              }
            } catch (e) {
              console.error('Error parsing SSE data:', e, 'Line:', line);
            }
          }
        }
      }
    } catch (error: any) {
      // 4. 捕获并处理中止错误
      if (error.name === 'AbortError') {
        console.log('API request was aborted by the user.');
        onMessage?.('', true); // 发送一个完成信号，以正常结束UI状态
      } else {
        // 重新抛出其他类型的错误
        throw error;
      }
    }
    // 3. 流式调用结束后，不再有返回值
  }
};

/**
 * 创建对话上下文
 * @param systemPrompt 系统提示词
 * @param userMessage 用户消息
 * @param history 历史对话记录
 */
export const createChatContext = (
  systemPrompt: string,
  userMessage: string,
  history: Message[] = []
): Message[] => {
  const messages: Message[] = [];
  
  // 1. 添加系统提示词 (仅当存在时)
  if (systemPrompt) {
    messages.push({
      role: 'system',
      content: systemPrompt
    });
  }
  
  // 2. 添加历史对话
  messages.push(...history);
  
  // 3. 添加当前用户消息 (仅当存在且不为空时)
  if (userMessage) {
    messages.push({
      role: 'user',
      content: userMessage
    });
  }
  
  return messages;
};
